<?php

namespace App\Models\Mp;

use App\Lib\WeApp\WeApp;
use Dcat\Admin\Traits\HasDateTimeFormatter;

use Illuminate\Database\Eloquent\Model;

class WxMpMessage extends Model
{
	use HasDateTimeFormatter;
    protected $table = 'wx_mp_message';

    public function normal(){
        if($this->msgtype == 'text'){
            return [
                "MsgType" => "text",
                "Content" => $this->content
            ];
        }else if($this->msgtype == 'image'){
            return [
                "MsgType" => "image",
                "Image" => [
                    "MediaId" => $this->media_id
                ]
            ];
        }else if($this->msgtype == 'voice'){
            return [
                "MsgType" => "voice",
                "Voice" => [
                    "MediaId" => $this->media_id
                ]
            ];
        }else if($this->msgtype == 'video'){
            return [
                "MsgType" => "video",
                "Video" => [
                    "MediaId" => $this->media_id,
                    "Title" => $this->title,
                    "Description" => $this->description
                ]
            ];
        }else if($this->msgtype == 'music'){
            return [
                "MsgType" => "music",
                "Music" => [
                    "MusicUrl" => $this->musicurl,
                    "HQMusicUrl " => $this->musicurl,
                    "ThumbMediaId" => $this->thumb_media_id,
                    "Title" => $this->title,
                    "Description" => $this->description
                ]
            ];
        }else if($this->msgtype == 'news' || $this->msgtype == 'mpnews'){
            return [
                "MsgType" => "news",
                "ArticleCount" => 1,
                "Articles" => [
                    [
                        "Title" => $this->title,
                        "Description" => $this->description,
                        "PicUrl" => $this->thumb_url,
                        "Url" => $this->url
                    ]
                ]
            ];
        }else if($this->msgtype == 'mpnews'){
            return [
                "MsgType" => "mpnewsarticle",
                "MpNewsArticle" => [
                    "ArticleId" => $this->article_id,
                ]
            ];
        }
    }

    protected static function boot()
    {
        parent::boot();

        static::creating(function ($model) {
            // 在模型创建之前触发的操作
            // 在模型创建之后触发的操作
            $weapp = new WeApp('mp');
            $mp = $weapp->getMpServicer();

            if($model->msgtype == 'text'){

            }else if($model->msgtype == 'image' || $model->msgtype == 'material_image'){
                if($model->img_url){
                    $img_url = $model->img_url;
                    try {
                        // 获取远程图片内容
                        $res = $mp->uploadMaterial($img_url);
                        if($res['code'] == 200){
                            $model->media_id = $res['media_id'];
                        }else{
                            throw new \Exception($res['msg']);
                        }
                    }catch (\Exception $e){
                        _logger_(__file__, __line__, $e->getMessage());
                    }
                }else{
                    throw new \Exception('请上传图片');
                }
            }else if($model->msgtype == 'voice' || $model->msgtype == 'material_voice'){
                if($model->voice_url){
                    $voice_url = $model->voice_url;
                    try {
                        // 获取远程图片内容
                        $res = $mp->uploadMaterial($voice_url, 'voice');
                        if($res['code'] == 200){
                            $model->media_id = $res['media_id'];
                        }else{
                            throw new \Exception($res['msg']);
                        }
                    }catch (\Exception $e){
                        _logger_(__file__, __line__, $e->getMessage());
                    }
                }else{
                    throw new \Exception('请上传语音');
                }
            }else if($model->msgtype == 'video' || $model->msgtype == 'material_video'){
                if($model->video_url && $model->title && $model->description && $model->thumb_url){
                    try {
                        // 获取远程图片内容
                        $res = $mp->uploadMaterial($model->video_url, 'video', $model->title, $model->description);
                        if($res['code'] == 200){
                            $model->media_id = $res['media_id'];
                            $thumb_url = $model->thumb_url;
                            try {
                                // 获取远程图片内容
                                $res2 = $mp->uploadMaterial($thumb_url);
                                if($res2['code'] == 200){
                                    $model->thumb_media_id = $res2['media_id'];
                                }else{
                                    throw new \Exception($res2['msg']);
                                }
                            }catch (\Exception $e){
                                _logger_(__file__, __line__, $e->getMessage());
                            }
                        }else{
                            throw new \Exception($res['msg']);
                        }
                    }catch (\Exception $e){
                        _logger_(__file__, __line__, $e->getMessage());
                    }
                }else{
                    throw new \Exception('有空的参数');
                }
            }else if($model->msgtype == 'music' || $model->msgtype == 'material_music'){
                if($model->thumb_url){
                    $thumb_url = $model->thumb_url;
                    try {
                        // 获取远程图片内容
                        $res = $mp->uploadMaterial($thumb_url);
                        if($res['code'] == 200){
                            $model->thumb_media_id = $res['media_id'];
                        }else{
                            throw new \Exception($res['msg']);
                        }
                    }catch (\Exception $e){
                        _logger_(__file__, __line__, $e->getMessage());
                    }
                }else{
                    throw new \Exception('请上传封面');
                }
            }else if($model->msgtype == 'news'){
//                throw new \Exception('暂只允许创建text和image类型的消息');
                if($model->thumb_url){
                    $thumb_url = $model->thumb_url;
                    try {
                        // 获取远程图片内容
                        $res = $mp->uploadMaterial($thumb_url);
                        if($res['code'] == 200){
                            $model->thumb_media_id = $res['media_id'];
                        }else{
                            throw new \Exception($res['msg']);
                        }
                    }catch (\Exception $e){
                        _logger_(__file__, __line__, $e->getMessage());
                    }
                }else{
                    throw new \Exception('请上传封面');
                }
            }else if($model->msgtype == 'mpnews'){
                if(_empty_($model->article_id) || strlen($model->article_id) < 50){
                    throw new \Exception('article_id错误');
                }
                $article_res = $mp->getArticle($model->article_id);
                if($article_res['code'] == 200){
                    $first_article = $article_res['news_item'][0];
                    $model->title = $first_article['title'];
                    $model->description = $first_article['digest'];
                    $model->url = $first_article['url'];
                    if($first_article['thumb_url']){
                        $model->thumb_url = $first_article['thumb_url'];
                        $model->thumb_media_id = $first_article['thumb_media_id'];
                    }else{
                        if(_array_key($first_article, 'thumb_media_id', '')){
                            $material_res = $mp->getMaterial($first_article['thumb_media_id']);
                            if($material_res['code'] == 200){
                                $model->thumb_url = $material_res['url'];
                                $model->thumb_media_id = $first_article['thumb_media_id'];
                            }
                        }
                    }
                }
            }else if($model->msgtype == 'wxcard'){
                throw new \Exception('暂不允许创建 卡卷类型');
            }else{
                throw new \Exception('无');
            }
        });

        static::created(function ($model) {

        });

        static::updating(function ($model) {
            // 在模型更新之前触发的操作
            $model->original = $model->getOriginal();
        });

        static::updated(function ($model) {
            $original = $model->original;
            $changes = $model->getChanges();

            $weapp = new WeApp('mp');
            $mp = $weapp->getMpServicer();

            // 对比更新前后的字段
            foreach ($changes as $key => $value) {
                if($model->msgtype == 'image' || $model->msgtype == 'material_image'){
                    if($key == 'img_url'){
                        $originalValue = $original[$key] ?? 0;
                        if($originalValue != $value){
                            $img_url = $value;
                            try {
                                // 获取远程图片内容
                                $res = $mp->uploadMaterial($img_url);
                                if($res['code'] == 200){
                                    $media_id = $model->media_id;
                                    WxMpMessage::where('id', $model->id)->update([
                                        'media_id' => $res['media_id']
                                    ]);
                                    $mp->deleteMaterial($media_id);
                                }else{
                                    throw new \Exception($res['msg']);
                                }
                            }catch (\Exception $e){
                                _logger_(__file__, __line__, $e->getMessage());
                            }
                        }
                    }
                }else if($model->msgtype == 'voice' || $model->msgtype == 'material_voice'){
                    if($key == 'voice_url'){
                        $voice_url = $value;
                        try {
                            $res = $mp->uploadMaterial($voice_url, 'voice');
                            if($res['code'] == 200){
                                $media_id = $model->media_id;
                                WxMpMessage::where('id', $model->id)->update([
                                    'media_id' => $res['media_id']
                                ]);
                                $mp->deleteMaterial($media_id);
                            }else{
                                throw new \Exception($res['msg']);
                            }
                        }catch (\Exception $e){
                            _logger_(__file__, __line__, $e->getMessage());
                        }
                    }
                }else if($model->msgtype == 'music' || $model->msgtype == 'material_music'){
                    if($key == 'thumb_url'){
                        $thumb_url = $value;
                        try {
                            // 获取远程图片内容
                            $res = $mp->uploadMaterial($thumb_url);
                            if($res['code'] == 200){
                                $thumb_media_id = $model->thumb_media_id;
                                WxMpMessage::where('id', $model->id)->update([
                                    'thumb_media_id' => $res['media_id']
                                ]);
                                $mp->deleteMaterial($thumb_media_id);
                            }else{
                                throw new \Exception($res['msg']);
                            }
                        }catch (\Exception $e){
                            _logger_(__file__, __line__, $e->getMessage());
                        }
                    }
                }else if($model->msgtype == 'video' || $model->msgtype == 'material_video'){
                    if($key == 'video_url'){
                        $res = $mp->uploadMaterial($model->video_url, 'video', $model->title, $model->description);
                        if($res['code'] == 200){
                            $media_id = $model->media_id;
                            WxMpMessage::where('id', $model->id)->update([
                                'media_id' => $res['media_id']
                            ]);
                            $mp->deleteMaterial($media_id);
                        }else{
                            throw new \Exception($res['msg']);
                        }
                    }else if($key == 'thumb_url'){
                        $thumb_url = $value;
                        try {
                            // 获取远程图片内容
                            $res = $mp->uploadMaterial($thumb_url);
                            if($res['code'] == 200){
                                $thumb_media_id = $model->thumb_media_id;
                                WxMpMessage::where('id', $model->id)->update([
                                    'thumb_media_id' => $res['media_id']
                                ]);
                                $mp->deleteMaterial($thumb_media_id);
                            }else{
                                throw new \Exception($res['msg']);
                            }
                        }catch (\Exception $e){
                            _logger_(__file__, __line__, $e->getMessage());
                        }
                    }
                }else if($model->msgtype == 'news'){
                    if($key == 'thumb_url'){
                        $thumb_url = $value;
                        try {
                            // 获取远程图片内容
                            $res = $mp->uploadMaterial($thumb_url);
                            if($res['code'] == 200){
                                $thumb_media_id = $model->thumb_media_id;
                                WxMpMessage::where('id', $model->id)->update([
                                    'thumb_media_id' => $res['media_id']
                                ]);
                                $mp->deleteMaterial($thumb_media_id);
                            }else{
                                throw new \Exception($res['msg']);
                            }
                        }catch (\Exception $e){
                            _logger_(__file__, __line__, $e->getMessage());
                        }
                    }
                }else if($model->msgtype == 'mpnews'){
                    if($key == 'article_id') {
                        $updates = [];
                        $article_res = $mp->getArticle($model->article_id);
                        if ($article_res['code'] == 200) {
                            $first_article = $article_res['news_item'][0];
                            $updates['title'] = $first_article['title'];
                            $updates['description'] = $first_article['digest'];
                            $updates['url'] = $first_article['url'];
                            if ($first_article['thumb_url']) {
                                $updates['thumb_url'] = $first_article['thumb_url'];
                                $updates['thumb_media_id'] = $first_article['thumb_media_id'];
                            } else {
                                if (_array_key($first_article, 'thumb_media_id', '')) {
                                    $material_res = $mp->getMaterial($first_article['thumb_media_id']);
                                    if ($material_res['code'] == 200) {
                                        $updates['thumb_url'] = $material_res['url'];
                                        $updates['thumb_media_id'] = $first_article['thumb_media_id'];
                                    }
                                }
                            }
                            $thumb_media_id = $model->thumb_media_id;
                            WxMpMessage::where('id', $model->id)->update($updates);
                            $mp->deleteMaterial($thumb_media_id);
                        }
                    }
                }
            }
        });
        // 其他的模型事件监听...

        static::deleting(function ($model) {
            // 在删除之前执行的逻辑
        });

        static::deleted(function ($model) {
            // 在删除之后执行的逻辑
            $weapp = new WeApp('mp');
            $mp = $weapp->getMpServicer();

            if($model->media_id){
                $mp->deleteMaterial($model->media_id);
            }
            if($model->thumb_media_id){
                $mp->deleteMaterial($model->thumb_media_id);
            }

            WxMpMessageReply::where('mp_message_id', $model->id)->delete();
        });

    }

}
